<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }" class="catalog">
    <div>
      <TitleBar title="目录" icon="fa fa-list-alt"></TitleBar>
      <div
        v-for="anchor in titles"
        :style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }"
        @click="handleAnchorClick(anchor)"
        :key="anchor"
      >
        <a style="cursor: pointer" class="catalog-link">{{ anchor.title }}</a>
      </div>
    </div>
  </el-card>
</template>

<script>
import bus from "@/eventbus.js";
import TitleBar from "@/components/common/TitleBar.vue";
export default {
  data() {
    return {
      titles: [],
      mdPreview: {},
    };
  },
  mounted() {
    bus.on("mdPreview", (o) => {
      this.$nextTick(() => {
        this.mdPreview = o;
        const anchors = o.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");
        const titles = Array.from(anchors).filter((title) => !!title.innerText.trim());
        if (!titles.length) {
          this.titles = [];
          return;
        }

        const hTags = Array.from(new Set(titles.map((title) => title.tagName))).sort();

        this.titles = titles.map((el) => ({
          title: el.innerText,
          lineIndex: el.getAttribute("data-v-md-line"),
          indent: hTags.indexOf(el.tagName),
        }));
      });
    });
  },
  methods: {
    handleAnchorClick(anchor) {
      const { preview } = this.$refs;
      const { lineIndex } = anchor;
      console.log(anchor);
      const heading = this.mdPreview.$el.querySelector(`[data-v-md-line="${lineIndex}"]`);
      if (heading) {
        this.mdPreview.scrollToTarget({
          target: heading,
          scrollContainer: window,
          top: 60,
        });
      }
    },
  },
  components: {
    TitleBar,
  },
};
</script>

<style scoped>
.catalog {
  margin-top: 16px;
}
:deep() .title,
:deep() #icon {
  font-size: 1.8rem;
  color: #34495e;
  font-weight: 700;
}
:deep() .container {
  justify-content: start;
  margin-top: 1rem;
  margin-bottom: 1rem;
}
.catalog-link {
  transition: 0.3s;
  color: black;
}
.catalog-link:hover {
  color: #43ceff;
}
.catalog-link:visited {
  color: gray;
}
</style>
